const app = getApp()
const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')

Page({
  data: {
    totalScoreToPay: 0,
    goodsList: [],
    isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJson: "",
    orderType: "", //订单类型，购物车下单或立即支付下单，默认是购物车，
    // pingtuanOpenId: undefined, //拼团的话记录团号

    hasNoCoupons: true,
    coupons: [],
    // youhuijine: 0, //优惠券金额
    // curCoupon: null, // 当前选择使用的优惠券
    allowSelfCollection: '0', // 是否允许到店自提
    // peisongType: 'zq' ,// 配送方式 kd,zq 分别表示快递/到店自取

    shopList:[],
    checked:false,//到店自取
    payButtonClicked:false,//防止支付连续点击
    popupShow:false,//地址弹窗
    addressList:[],
    groupNo: ""
  },

  // 获取地址列表
  initAddress: function () {
    var that = this;
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        WXAPI.queryAddress().then(function (res) {
          if (res.retCode == "200") {
            that.setData({
              addressList: res.data
            });
          } else {
            wx.showModal({
              title: '错误',
              content: res.retMsg,
              showCancel: false
            })
          }
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              // wx.switchTab({
              //   url: "/pages/my/index?page=toPay"
              // })
              wx.navigateTo({
                url: '/pages/my/index?page=toPay',
              })
            } else {
              wx.navigateBack()
            }
          }
        })
      }
    })

   
  },
  // 选中地址
  selectTap: function (e) {
    var id = e.currentTarget.dataset.id;
    const selectAdd = this.data.addressList.filter(item => item.id === id)[0];
    this.onClose();
    this.setData({
      curAddressData: selectAdd,
    })
  },
  // 新增地址
  addAddess: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  onChange({ detail }){
    console.log(detail)
    if (detail){
      this.getShopAdd();
    }
    this.setData({ checked: detail });
  },
  getShopAdd(){
    let that = this;
    if (app.globalData.shopNo && app.globalData.shopNo != ''){
      WXAPI.getShopAddress().then(function (res) {
        if (res.retCode === '200') {
          console.log(res)
          that.setData({
            shopAddress: res.data,
          })
        } else {
          wx.showModal({
            title: '错误',
            content: res.retMsg,
            showCancel: false
          })

        }
        // that.processYunfei();
      })
    }else{
      setTimeout(function () {
        that.getShopAdd();
      }, 300)
    }
    
  },
  onShow(){
    if (this.data.popupShow){
      this.initAddress();
    }
  },
  doneShow: function () {
    // let allowSelfCollection = wx.getStorageSync('ALLOW_SELF_COLLECTION')
    // if (!allowSelfCollection || allowSelfCollection != '1') {
    //   allowSelfCollection = '0'
    //   this.data.peisongType = 'kd'
    // }
    const that = this;
    // console.log("orderType=", that.data.orderType)
    //立即购买下单
    // if ("buyNow" == that.data.orderType) {     
    //   var buyNowInfoMem = wx.getStorageSync('buyNowInfo');
    //   that.data.kjId = buyNowInfoMem.kjId;
    //   if (buyNowInfoMem && buyNowInfoMem.shopList) {
    //     shopList = buyNowInfoMem.shopList
    //   }
    // } else {
    //   //购物车下单
    //   var shopCarInfoMem = wx.getStorageSync('shopCarInfo');
    //   that.data.kjId = shopCarInfoMem.kjId;
    //   if (shopCarInfoMem && shopCarInfoMem.shopList) {
    //     // shopList = shopCarInfoMem.shopList
    //     shopList = shopCarInfoMem.shopList.filter(entity => {
    //       return entity.active;
    //     });
    //   }
    // }

    // that.setData({
    //   goodsList: shopList,
    //   allowSelfCollection: allowSelfCollection,
    //   peisongType: that.data.peisongType
    // });
    // that.initShippingAddress();
  },
  // 获取商店商品数量和合计金额
  setNumVal(){
    let that = this;
    let shopList = [];
    let goodsVal;
    let allGoodVal = 0;
    // 获取购物车数据
    var shopCarInfoMem = wx.getStorageSync('buyNowInfo');
    console.log(shopCarInfoMem)
    if (shopCarInfoMem && shopCarInfoMem.length > 0) {
      shopList = shopCarInfoMem;

      // 设置商店内的购买商品数量和总价
      for (let arrItem of shopList) {
        goodsVal = 0;
        for (let listItem of arrItem.list) {
          goodsVal += listItem.buyMoney;
        }
        arrItem.goodsNum = arrItem.list.length;
        arrItem.goodsVal = goodsVal;
        allGoodVal += arrItem.goodsVal;
      }
    }
    
    that.setData({
      shopList: shopList,
      allGoodsAndYunPrice: allGoodVal,
    })

  },
  onLoad: function (e) {
    this.setNumVal();
    let _data = {
      isNeedLogistics: 1,
    }
    if (e.orderType) {
      _data.orderType = e.orderType
    }
    if (e.groupNo && e.groupNo !== "undefined") {
      _data.groupNo = e.groupNo
    }
    this.setData(_data);
  },
  
  onUnload(){
    // wx.removeStorage({ key: 'buyNowInfo' });
  },

  // 退出或下单之后处理参数
  toCheckGoodsInfo(orderState){
    let that = this;
    wx.removeStorage({ key: 'buyNowInfo' });
    // 购物车的订单，退出删除
    if (that.data.orderType == '' && orderState == 'afterOrder'){
      wx.getStorage({
        key: 'shopCarInfo',
        success: function(res) {
          if(res.data && res.data.length > 0){
            let resArr = res.data;
            // 删除购物车的选中订单
            for (let [ind, arrItem] of resArr.entries()) {
              for (let [index, listItem] of arrItem.list.entries()) {
                if (listItem.checked) {
                  arrItem.list.splice(index, 1);
                  if (arrItem.list.length == 0) {
                    resArr.splice(ind, 1);
                  }
                }
              }
            }
            wx.setStorage({
              key: 'shopCarInfo',
              data: resArr
            })

          }
        },
      })
    }
  },

  getDistrictId: function (obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },

  createOrder: function (e) {
    var that = this;
    // var loginToken = wx.getStorageSync('token') // 用户登录 token
    // var remark = ""; // 备注信息
    // if (e) {
    //   remark = e.detail.value.remark; // 备注信息
    // }
    console.log("this.data=",this.data)

    // let postData = {
    //   payType:"0",
    //   orderSource:"0",
    //   orderCreateDetailVos: that.data.goodsJson,
    //   buylerMemo: remark,
    //   recvName:"张三",
    //   recvPhone:"1236547",
    //   recvProvince:"山东",
    //   recvCity:"济南",
    //   recvDistrict:"历下",
    //   recvAddress:"测试地址",
    //   recvZip:"236410",
    //   shippingAmt:"0.00"
    // };
    

    if (that.data.shopList.length < 1){
      wx.showModal({
        title: '错误',
        content: '请选择商品！',
        showCancel: false
      })
    }
    let curAddressData = that.data.curAddressData;
    let shopAddress = that.data.shopAddress;
    if ((curAddressData && curAddressData.recvName != '' && curAddressData.recvAddress != '' && curAddressData.recvCity != '' && curAddressData.recvDistrict != '' && curAddressData.recvMobile != '' && curAddressData.recvProvince != '' && !that.data.checked) || (that.data.checked && shopAddress && shopAddress.shopName != '' && shopAddress.contactAddr != '')) {

      if (this.data.payButtonClicked) {
        wx.showToast({
          title: '休息一下~',
          icon: 'none'
        })
        return
      }
      this.data.payButtonClicked = true
      setTimeout(() => {
        this.data.payButtonClicked = false
      }, 3000)  // 可自行修改时间间隔（目前是3秒内只能点击一次支付按钮）


      let goodsArr = [];
      let goodObj = {};
      for (let goodItem of that.data.shopList[0].list) {
        goodObj = {
          "buyNum": goodItem.buyNumber + '',
          "itemNo": goodItem.itemNo,
          "stockNo": goodItem.stockNo
        };
        goodsArr.push(goodObj);
      }

      let orderType = that.data.orderType;
      let money = that.data.allGoodsAndYunPrice;
      let postData = {
        "buylerMemo": "",
        "orderCreateDetailVos": goodsArr,
        "recvAddress": curAddressData.recvAddress,
        "recvCity": curAddressData.recvCity,
        "recvDistrict": curAddressData.recvDistrict,
        "recvName": curAddressData.recvName,
        "recvPhone": curAddressData.recvMobile,
        "recvProvince": curAddressData.recvProvince,
        "shippingAmt": "0.00",
        "shopNo": that.data.shopList[0].shopNo,
        "groupNo": that.data.groupNo
      }
      // console.log(JSON.stringify(postData))
      WXAPI.orderCreate(postData).then(function (res) {
        if (res.retCode != "200") {
          wx.showModal({
            title: '错误',
            content: res.retMsg,
            showCancel: false
          })
          return;
        }
        if (e && "buyNow" != orderType) {
          // that.toCheckGoodsInfo('afterOrder');
          wx.removeStorage({ key: 'buyNowInfo' });
          // 购物车的订单，退出删除
          wx.getStorage({
            key: 'shopCarInfo',
            success: function (res) {
              if (res.data && res.data.length > 0) {
                let resArr = res.data;
                // 删除购物车的选中订单
                for (let [ind, arrItem] of resArr.entries()) {
                  for (let [index, listItem] of arrItem.list.entries()) {
                    if (listItem.checked) {
                      arrItem.list.splice(index, 1);
                      if (arrItem.list.length == 0) {
                        resArr.splice(ind, 1);
                      }
                    }
                  }
                }

                for (let [ind, arrItem] of resArr.entries()){
                  if (arrItem.checked){
                    resArr.splice(ind, 1);
                  }else{
                    // for (let [index, listItem] of arrItem.list.entries()) {
                    for (let i = arrItem.list.length - 1; i >= 0 ; i--) {
                      if (arrItem.list[i].checked) {
                        arrItem.list.splice(i, 1);
                      }
                    }
                  }
                }

                if (resArr.length > 0){
                  wx.setStorage({
                    key: 'shopCarInfo',
                    data: resArr
                  })
                }else{
                  wx.removeStorage({key: 'shopCarInfo'})
                }
                
              }
            },
          })
        }

        app.getGoodsNo();

        const that = this;
        const orderId = res.data;
        
        const postData = {
          orderNo: orderId
        }
        WXAPI.userAmount(postData).then(function (res) {
          console.log('res--0-', res)
          if (res.retCode === '200') {
            // 增加提示框
            let _msg = '订单金额: ' + money + ' 元';
            const payData = res.data
            // console.log(payData)
            wx.showModal({
              title: '请确认支付',
              content: _msg,
              confirmText: "确认支付",
              cancelText: "取消支付",
              success: function (res) {
                console.log(res);
                if (res.confirm) {
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr,
                    package: payData.package,
                    signType: 'MD5',
                    paySign: payData.sign,
                    fail: function (aaa) {
                      wx.showToast({
                        title: '支付失败:' + aaa
                      })
                      wx.reLaunch({
                        url: "/pages/order-list/index"
                      });
                    },
                    success: function () {
                      
                      // 提示支付成功
                      wx.showToast({
                        title: '支付成功'
                      })
                      wx.reLaunch({
                        url: "/pages/order-list/index"
                      });
                    }
                  })
                } else {
                  console.log('用户点击取消支付')
                }
              }
            });
          } else {
            wx.showModal({
              title: '错误',
              content: '无法获取用户资金信息',
              showCancel: false
            })
          }
        })
      })
    }else{
      wx.showModal({
        title: '错误',
        content: '请选择配送地址！',
        showCancel: false
      })
    }

  },
  initShippingAddress: function () {
    var that = this;
    if (!that.data.curAddressData){
      WXAPI.defaultAddress().then(function (res) {
        if (res.retCode === '200') {
          that.setData({
            curAddressData: res.data,
          });
        } else {
          that.setData({
            curAddressData: null,
          });

        }
        // that.processYunfei();
      })
    }
    
  },
  processYunfei: function () {
    var that = this;
    var goodsList = this.data.goodsList;
    var goodsJson = [];
    var isNeedLogistics = 1;
    var allGoodsPrice = 0;


    let inviter_id = 0;
    let inviter_id_storge = wx.getStorageSync('referrer');
    if (inviter_id_storge) {
      inviter_id = inviter_id_storge;
    }
    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];
      if (carShopBean.logistics) {
        isNeedLogistics = 1;
      }
      allGoodsPrice += carShopBean.price * carShopBean.number;

      // {"payType":"0","orderSource":"0","orderCreateDetailVos":[{"itemNo":"007","buyNum":1}],"buylerMemo":"","recvName":"李四","recvPhone":"020-8116788","recvProvince":"北京市","recvCity":"北京市","recvDistrict":"历下","recvAddress":"新港中路397号","recvZip":"236410","shippingAmt":"0.00"}

     /** goodsJsonStrTmp += '{"itemNo":' + carShopBean.goodsId + ',"buyNum":' + carShopBean.number + ',"propertyChildIds":"' + carShopBean.propertyChildIds + '","logisticsType":0, "inviter_id":' + inviter_id + '}';**/
     // goodsJsonStrTmp += '{"itemNo":' + carShopBean.goodsId + ',"buyNum":' + carShopBean.number + '}';
     console.log('0-0',allGoodsPrice)
      var itemObj={
        itemNo: carShopBean.goodsId,
        buyNum: carShopBean.number
      }
      goodsJson.push(itemObj);
     // goodsJsonStr += goodsJsonStrTmp;


    }
    //goodsJsonStr += "]";
    console.log(goodsJson);
    that.setData({
      isNeedLogistics: isNeedLogistics,
      goodsJson: goodsJson,
      allGoodsAndYunPrice: allGoodsPrice
    });
    // that.createOrder();
  },
  addAddress: function () {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },
  addWxAddress(){
    var that = this;
    if (wx.chooseAddress) {
      wx.chooseAddress({
        success: function (res) {
          console.log(res)
          that.setData({
            curAddressData:{
              recvName: res.userName,
              recvMobile: res.telNumber,
              recvName: res.userName,
              recvProvince: res.provinceName,
              recvCity: res.cityName,
              recvDistrict: res.countyName,
              recvAddress: res.detailInfo,
            }
          })
        },
        fail: function (res) {
          console.log(res)
        }
      })
    } else {
      // 如果希望用户在最新版本的客户端上体验您的小程序，可以这样子提示
      wx.showLoading({
        title: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
      })
    } 
  },
  selectAddress: function () {
    // wx.navigateTo({
    //   url: "/pages/select-address/index"
    // })
    this.setData({ popupShow: true });
    this.initAddress();
  },
  onClose() {
    this.setData({ popupShow: false });
  },
  bindChangeCoupon: function (e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      return;
    }
    //console.log("selIndex:" + selIndex);
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
  },
  radioChange (e) {
    this.setData({
      peisongType: e.detail.value
    })
  }
})